﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Backend.JYD.RunTime;
using Backend.JYD.BLL.Task;
using Backend.JYD.BLL.Cust;
using Backend.JYD.Model.Task;
using Backend.JYD.Business;
using Backend.JYD.BLL;
using Backend.JYD.Common;
using Backend.JYD.Model;
using Backend.JYD.RunTime.Attribute;

namespace Backend.JYD.Web.Controllers
{
    public class TaskController : BaseController
    {
        //
        // GET: /Task/
        private TaskBaseInfoBLL bll = new TaskBaseInfoBLL();
        private TaskStepInfoBLL bllStep = new TaskStepInfoBLL();
        public ActionResult Index(int? page, DateTime? start, DateTime? end, string status, string code, string old)
        {
            if (!page.HasValue || page <= 0) page = 1;
            PageInfo<TaskBaseInfo> infos = null;
            //if (old == "1")
            //{
            //    infos = bll.GetOldTaskBaseInfoByEmpInfo(new Model.PageInfo() { PageIndex = NumberHelper.ObjectToInt(page, 1), PageSize = 20 }, this.RoleIds, this.EmpId, start, end, status, code);
            //}
            //else
            {
                infos = bll.GetTaskBaseInfoByEmpInfo(new Model.PageInfo() { PageIndex = NumberHelper.ObjectToInt(page, 1), PageSize = BaseController.PageSize20 }, this.RoleIds, this.EmpId, start, end, status, code);
            }

            this.ViewBag.TaskModels = TaskManager.LoadDefaultTaskStepModel();
            if (infos == null || infos.PageList == null) return View();

            List<long> ids = new List<long>();
            foreach (var info in infos.PageList)
            {
                if (!ids.Contains(info.TaskId)) ids.Add(info.TaskId);
            }
            ids.Clear();
            List<long> roleIds = new List<long>();
            List<TaskStepModel> stepModels = new List<TaskStepModel>();
            foreach (var info in infos.PageList)
            {
                if (info.OpId.HasValue) ids.Add(info.OpId.Value);
                if (!string.IsNullOrWhiteSpace(info.EmpIds))
                {
                    var tmpIds = StringHelper.String2List<Int64>(info.EmpIds);
                    ids.AddRange(tmpIds);
                }
                if (!string.IsNullOrWhiteSpace(info.RoleIds))
                {
                    var tmpIds = StringHelper.String2List<Int64>(info.RoleIds);
                    roleIds.AddRange(tmpIds);
                }
                if (!stepModels.Exists(p => p.StepId == info.StepId))
                {
                    var stepModel = new TaskStepModelBLL().GetTaskStepModelByTaskModeIdAndStepId(info.TaskModelId, info.StepId);
                    if (stepModel != null)
                    {
                        stepModels.Add(stepModel);
                    }
                }
            }
            if (ids != null && ids.Count > 0)
            {
                ids = ids.Distinct().ToList();
                this.ViewBag.EmpInfos = new EmpInfoBLL().GetEmpInfoByEmpIds(ids, true);
            }
            if (roleIds != null && roleIds.Count > 0)
            {
                roleIds = roleIds.Distinct().ToList();
                this.ViewBag.RoleInfos = new RoleManager().GetRoleInfoByRoleIds(roleIds);
            }
            this.ViewBag.TaskStepModeles = stepModels.ToList();

            this.ViewBag.PageIndex = infos.PageIndex;
            this.ViewBag.PageSize = infos.PageSize;
            this.ViewBag.PageCount = infos.PageCount;
            this.ViewBag.ItemCount = infos.ItemCount;


            string url = "/task/index?page={0}";
            if (!string.IsNullOrWhiteSpace(code))
            {
                ViewBag.Code = code;
                url += "&code=" + code;
            }
            if (start.HasValue)
            {
                ViewBag.StartDate = DateTimeHelper.GetDateShortFormat(start.Value);
                url += "&start=" + DateTimeHelper.GetDateShortFormat(start.Value);
            }
            if(end.HasValue)
            {
                ViewBag.EndDate = DateTimeHelper.GetDateShortFormat(end.Value);
                url += "&end=" + DateTimeHelper.GetDateShortFormat(end.Value);
            }
            if (!string.IsNullOrWhiteSpace(status))
            {
                ViewBag.Status = status;
                url += "&status=" + status;
            }
            
            ViewBag.PageUrl = url;
            return View(infos.PageList);
        }

        //public ActionResult Commit(Int64 detailId, int type)
        //{
        //    if (detailId <= 0)
        //    {
        //        //return RedirectToAction("Index");
        //        return Json(new { returnCode = 0 }, JsonRequestBehavior.AllowGet);
        //    }
        //    var mgr = new TaskManager();
        //    var bllStep = new TaskStepInfoBLL();
        //    var stepInfo = bllStep.GetTaskStepInfoByTaskDetailId(detailId);
        //    if (stepInfo == null)
        //    {
        //        //return RedirectToAction("Index");
        //        return Json(new { returnCode = 0 }, JsonRequestBehavior.AllowGet);
        //    }
        //    //0-未处理；1-处理中；2-已完成，进入下一步；3-已退回；4-已完成，进入循环步骤；5-已结束-终止
        //    if (type == (int)TaskManager.TaskStatus.Processing)
        //    {
        //        stepInfo.Status = (int)TaskManager.TaskStatus.Processing;
        //        mgr.BeginProcessStep(stepInfo);
        //        //return RedirectToAction("Index");
        //    }
        //    else if (type == (int)TaskManager.TaskStatus.CompleteAndReady)
        //    {
        //        //return RedirectToAction("Handout");
        //    }
        //    else if (type == (int)TaskManager.TaskStatus.ReturnToLast || type == (int)TaskManager.TaskStatus.CompleteAndLoop || type == (int)TaskManager.TaskStatus.Complete)
        //    {
        //        stepInfo.Status = type;
        //        mgr.NextStep(stepInfo);
        //        //return RedirectToAction("Index");
        //    }
        //    return Json(new { returnCode = 1 }, JsonRequestBehavior.AllowGet);
        //    //return RedirectToAction("Index");
        //}

        public ActionResult Details(string id)
        {
            var task = bll.GetTaskBaseInfoByTaskId(NumberHelper.StrToInt64(id));
            if (task == null) return View();

            var list = bllStep.GetTaskStepInfoByTaskId(NumberHelper.StrToInt64(id));
            if (list == null) return View();
            
            list = list.OrderBy(p => p.CreateTime).ToList();
            List<long> ids = new List<long>();
            List<long> roleIds = new List<long>();
            List<TaskStepModel> stepModels = new List<TaskStepModel>();
            foreach (var info in list)
            {
                if (info.OpId.HasValue) ids.Add(info.OpId.Value);
                if (!string.IsNullOrWhiteSpace(info.EmpIds))
                {
                    var tmpIds = StringHelper.String2List<Int64>(info.EmpIds);
                    ids.AddRange(tmpIds);
                }
                if (!string.IsNullOrWhiteSpace(info.RoleIds))
                {
                    var tmpIds = StringHelper.String2List<Int64>(info.RoleIds);
                    roleIds.AddRange(tmpIds);
                }
                if (!stepModels.Exists(p => p.StepId == info.StepId))
                {
                    var stepModel = new TaskStepModelBLL().GetTaskStepModelByTaskModeIdAndStepId(task.TaskModelId, info.StepId);
                    if (stepModel != null)
                    {
                        stepModels.Add(stepModel);
                    }
                }
            }
            if (ids != null && ids.Count > 0)
            {
                ids = ids.Distinct().ToList();
                this.ViewBag.EmpInfos = new EmpInfoBLL().GetEmpInfoByEmpIds(ids, true);
            }
            if (roleIds != null && roleIds.Count > 0)
            {
                roleIds = roleIds.Distinct().ToList();
                this.ViewBag.RoleInfos = new RoleManager().GetRoleInfoByRoleIds(roleIds);
            }
            this.ViewBag.TaskStepModeles = stepModels.ToList();
            return View(list);
        }

        public ActionResult Error(int id, Int64 taskId, TaskManager.StepModelCode? code, string next, bool? useRole)
        {
            //id=1, 存在不允许执行该操作的任务。
            this.ViewBag.Type = id;
            this.ViewBag.TaskId = taskId;
            string codeName = string.Empty;
            if (id == 2 || id == 3)
            {
                codeName = useRole.Value ? "执行角色" : "执行人";
            }
            else if (code == TaskManager.StepModelCode.HandOut)
            {
                codeName = "分配";
            }
            else if(code == TaskManager.StepModelCode.Marketing)
            {
                codeName = "跟踪";
            }
            this.ViewBag.Code = codeName;
            return View();
        }

        private TaskBaseInfo baseInfo = null;
        private TaskStepModel currModel = null;
        private List<TaskStepModel> stepModeles = null;
        private TaskManager taskMgr = new TaskManager();

        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager, AuthorCode.AuthorCode_TaskHandOut)]
        public ActionResult Next(string id)
        {
            #region 验证数据

            var errId = this.CheckTaskInfo(id);
            if (errId > 0)
            {
                return RedirectToAction("error", new { id = errId, taskId = id, code = this.currModel == null ? string.Empty : this.currModel.StepCode });
            }

            #endregion

            #region 下一步step
            var nextStepIds = StringHelper.String2List<Int32>(this.currModel.NextStepIds);
            if (nextStepIds == null || nextStepIds.Count <= 0)
            {
                return RedirectToAction("error", new { id = 12 });
            }
            var nextModeles = this.stepModeles.FindAll(p => nextStepIds.Contains(p.StepId));
            this.ViewBag.NextModeles = nextModeles;
            this.ViewBag.TaskId = this.baseInfo.TaskId;

            #endregion

            return View();
        }
        [HttpPost]
        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager, AuthorCode.AuthorCode_TaskHandOut)]
        public ActionResult Next(string id, FormCollection collection)
        {
            #region 验证数据

            string chkId = collection["chkId"];
            string remark = collection["remark"];
            string stepId = collection["rdoStepId"];
            if (string.IsNullOrWhiteSpace(stepId))
            {
                return Json(new { code = false, msg = "请选择步骤" });
            } 
             if (string.IsNullOrWhiteSpace(chkId))
            {
                return Json(new { code = false, msg = "请选择下一步骤执行者" });
            }
            var errId = this.CheckTaskInfo(id);
            if (errId > 0)
            {
                return Json(new { code = false, msg = "验证未通过" });
            }

            #endregion

            #region 执行任务，下一步

            TaskStepInfo step = new TaskStepInfo();
            step.TaskId = this.baseInfo.TaskId;
            step.TaskDetailId = this.baseInfo.TaskDetailId.Value;
            step.Remark = remark;
            step.Status = (int)TaskManager.TaskStatus.CompleteAndReady;
            if (currModel.UseRole)
            {
                step.RoleIds = chkId;
            }
            else
            {
                step.EmpIds = chkId;
            }
            var chkIds = StringHelper.String2List<Int64>(chkId);
            var nextStepId = NumberHelper.StrToInt(stepId);
            bool success = this.taskMgr.NextStep(this.baseInfo.TaskId, chkIds, TaskManager.TaskStatus.CompleteAndReady, nextStepId, remark, this.EmpId);
            if (success)
            {
                return Json(new { code = true });
            }
            else
            {
                LogHelper.Log("任务：" + this.baseInfo.TaskId + " 执行失败", null);
                return Json(new { code = false, msg = "执行失败" });
            }
            #endregion
        }

        /// <summary>
        /// 单个处理
        /// </summary>
        /// <param name="id"></param>
        /// <param name="code"></param>
        /// <param name="next">操作代码</param>
        /// <returns></returns>
        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager, AuthorCode.AuthorCode_TaskHandOut)]
        public ActionResult Process(string id)
        {
            #region #region 当前模型, 检查操作是否允许 

            var errId = this.CheckTaskInfo(id);
            if (errId > 0)
            {
                return RedirectToAction("error", new { id = errId, taskId = id, code = this.currModel == null ? string.Empty : this.currModel.StepCode });
            }

            if (this.currModel.StepCode.ToLower() == TaskManager.StepModelCode.Marketing.ToString().ToLower()
                || this.currModel.StepCode.ToLower() == TaskManager.StepModelCode.HandOut.ToString().ToLower())
            {
                return RedirectToAction("error", new { id = 7 });
            }

            #endregion

            return View();
        }
        [HttpPost]
        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager, AuthorCode.AuthorCode_TaskHandOut)]
        public ActionResult Process(string id, FormCollection collection)
        {
            try
            {

                #region 页面数据获取

                string remark = collection["remark"];

                var errId = this.CheckTaskInfo(id);
                if (errId > 0)
                {
                    return RedirectToAction("error", new { id = errId, taskId = id, code = this.currModel == null ? string.Empty : this.currModel.StepCode });
                }

                #endregion

                #region 执行任务，开始处理

                this.taskMgr.BeginProcessStep(this.baseInfo.TaskId, this.EmpId, remark);

                #endregion

                return Json(new { code = true });
            }
            catch (Exception ex)
            {
                LogHelper.Log(ex);
                return Json(new { code = false, msg = "异常" });
            }
        }

        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager)]
        public ActionResult Last(string id)
        {
            #region 验证数据

            var errId = this.CheckTaskInfo(id);
            if (errId > 0)
            {
                return RedirectToAction("error", new { id = errId, taskId = id, code = this.currModel == null ? string.Empty : this.currModel.StepCode });
            }

            #endregion

            #region 下一步step
            var lastStepIds = StringHelper.String2List<Int32>(this.currModel.LastStepIds);
            if (lastStepIds == null || lastStepIds.Count <= 0)
            {
                return RedirectToAction("error", new { id = 12 });
            }
            var lastModeles = this.stepModeles.FindAll(p => lastStepIds.Contains(p.StepId));
            this.ViewBag.LastModeles = lastModeles;

            #endregion

            return View();
        }
        [HttpPost]
        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager)]
        public ActionResult Last(string id, FormCollection collection)
        {
            #region 验证数据

            string remark = collection["remark"];
            string stepId = collection["rdoStepId"];
            if (string.IsNullOrWhiteSpace(stepId))
            {
                return Json(new { code = false, msg = "请选择返回步骤" });
            }
            var errId = this.CheckTaskInfo(id);
            if (errId > 0)
            {
                return Json(new { code = false, msg = "验证未通过" });
            }

            #endregion

            #region 执行任务，返回

            var lastStepId = NumberHelper.StrToInt(stepId);
            bool success = this.taskMgr.NextStep(this.baseInfo.TaskId, null, TaskManager.TaskStatus.ReturnToLast, lastStepId, remark, this.EmpId);
            if (success)
            {
                return Json(new { code = true });
            }
            else
            {
                LogHelper.Log("任务：" + this.baseInfo.TaskId + " 执行失败", null);
                return Json(new { code = false, msg = "执行失败" });
            }
            #endregion
        }

        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager)]
        public ActionResult Loop(string id)
        {
            #region #region 当前模型, 检查操作是否允许

            var errId = this.CheckTaskInfo(id);
            if (errId > 0)
            {
                return RedirectToAction("error", new { id = errId, taskId = id, code = this.currModel == null ? string.Empty : this.currModel.StepCode });
            }

            if (this.currModel.StepCode.ToLower() == TaskManager.StepModelCode.Marketing.ToString().ToLower()
                || this.currModel.StepCode.ToLower() == TaskManager.StepModelCode.HandOut.ToString().ToLower())
            {
                return RedirectToAction("error", new { id = 7 });
            }

            #endregion

            return View();
        }
        [HttpPost]
        [AuthorityFilter(AuthorCode.AuthorCode_TaskManager)]
        public ActionResult Loop(string id, FormCollection collection)
        {
            #region 验证数据

            string remark = collection["remark"];
            var errId = this.CheckTaskInfo(id);
            if (errId > 0)
            {
                return Json(new { code = false, msg = "验证未通过" });
            }

            #endregion

            #region 执行任务，返回

            bool success = this.taskMgr.NextStep(this.baseInfo.TaskId, null, TaskManager.TaskStatus.CompleteAndLoop, null, remark, this.EmpId);
            if (success)
            {
                return Json(new { code = true });
            }
            else
            {
                LogHelper.Log("任务：" + this.baseInfo.TaskId + " 执行失败", null);
                return Json(new { code = false, msg = "执行失败" });
            }
            #endregion
        }


        //数据验证
        private int CheckTaskInfo(string id)
        {
            var taskId = NumberHelper.StrToInt(id);
            if (taskId <= 0)
            {
                return 4;
            }
            this.baseInfo = bll.GetTaskBaseInfoByTaskId(taskId);
            if (baseInfo == null)
            {
                return 4;
            }
            this.stepModeles = TaskManager.LoadTaskStepModelByTaskModeId(baseInfo.TaskModelId);
            if (this.stepModeles == null)
            {
                return 4;
            }

            this.currModel = this.stepModeles.Find(p => p.StepId == baseInfo.StepId);
            if (this.currModel == null)
            {
                return 4;
            }
            else if (this.currModel.StepCode.ToLower() == TaskManager.StepModelCode.Marketing.ToString().ToLower())
            {
                return 7;
            }
            TaskManager.StepModelCode? enumModelCode = null;
            if (!string.IsNullOrWhiteSpace(this.currModel.StepCode))
            {
                enumModelCode = TaskManager.GetStepModelCodeByStepCode(this.currModel.StepCode);
            }
            bool allow = this.taskMgr.CheckTaskStepModel(baseInfo, this.currModel, enumModelCode, TaskManager.TaskStatus.CompleteAndReady);
            return !allow ? 1 : 0;
        }
    }
}
